//
//  HMEmoticonPageView.swift
//  WB25
//
//  Created by HM on 2017/7/10.
//  Copyright © 2017年 itheima. All rights reserved.
//

import UIKit
// cell可重用标识符
private let HMEmoticonPageViewCellId = "HMEmoticonPageViewCellId"
class HMEmoticonPageView: UICollectionView {

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        // layout
        let flowLayout = UICollectionViewFlowLayout()
        // 设置垂直和水瓶间距
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        // 滚动方向
        flowLayout.scrollDirection = .horizontal
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置视图
    private func setupUI(){
//        backgroundColor = randomColor()
        dataSource = self
        register(HMEmoticonPageViewCell.self, forCellWithReuseIdentifier: HMEmoticonPageViewCellId)
        // 因为在滚动到制定组和页数的时候 可能cell还没有实例化成功 导致不能成功 使用主线程异步等到主线程任务完成后在执行闭包中的代码
        DispatchQueue.main.async { 
            // 设置默认滚动到第一组第零页
            self.scrollToItem(at: IndexPath(item: 0, section: 1), at: UICollectionViewScrollPosition.left, animated: false)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 获取layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 设置itemSize
        layout.itemSize = self.frame.size
            }

}
//MARK: - UICollectionViewDataSource
extension HMEmoticonPageView: UICollectionViewDataSource{
    // 返回组数
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return HMEmoticonTools.share.allEmoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonTools.share.allEmoticons[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMEmoticonPageViewCellId, for: indexPath) as! HMEmoticonPageViewCell
        cell.indexPath = indexPath
        cell.emoticons = HMEmoticonTools.share.allEmoticons[indexPath.section][indexPath.item]
        return cell
    }
}
